<template>
  <!-- 手动分案-公共组件 -->
  <section class="component case-allot">
    <el-row style="margin-bottom:15px">
      <span>分配方式：</span>
      <el-radio-group v-model="allotType" size="small">
        <el-radio border label="TO_COLLECTOR">按催收员分配</el-radio>
        <el-radio border label="TO_DEPARTMENT">按机构分配</el-radio>
      </el-radio-group>
    </el-row>
    <el-row type="flex">
      <el-col :span="6" style="height:400px;margin-top:4px;border:1px solid #d1dbe5;overflow:auto">
        <department-tree @onCurrentChange="getCheckedNodes" v-model="currentDept" :departmentData="DepartmentData" ref="department-tree"></department-tree>
      </el-col>
      <el-col :span="18">
        <data-box :page="pageService" :selectionList.sync="display" :data="userDataSet" @onPageChange="refreshData" ref="data-box">
          <template slot="columns">
            <el-table-column prop="userName" label="用户名" :min-width="$helper.getColumnWidth(3)"></el-table-column>
            <el-table-column prop="realName" label="姓名" :min-width="$helper.getColumnWidth(3)"></el-table-column>
            <el-table-column prop="deptName" label="所属机构" :min-width="$helper.getColumnWidth(3)"></el-table-column>
          </template>
        </data-box>
      </el-col>
    </el-row>
    <div v-if="isShow" style="padding-top:20px;overflow:hidden" class="days-title">
      <span style="float:left;line-height:26px;">催收天数：</span>
      <el-input style="float:left;width:150px" placeholder="请输入催收天数" type="number" v-model="personalCollectionDays"></el-input>
      <span style="float:left;line-height:26px;">天</span>
    </div>
    <div style="text-align:center;margin-top:30px;">
      <el-button @click="emitClose">取消</el-button>
      <el-button @click="next" v-if="allotType === 'TO_COLLECTOR'" :disabled="!selectionList.length">下一步</el-button>
      <el-button @click="submit" :loading="submitLoading" v-else>确定</el-button>
    </div>

    <el-dialog title="确认分案" :visible.sync="dialog" width="1000px" :close-on-click-modal="false" :close-on-press-escape="false" @open="$nextTick(()=>$refs['distribution'].refreshData())" append-to-body>
      <distribution :again="again" :fromChannel="fromChannel" @success="success" @back="dialog=false" @close="emitClose" ref="distribution"></distribution>
    </el-dialog>
    <!-- 信息修复确认分案 -->
    <el-dialog title="确认分案" :visible.sync="dialogMessage" width="1000px" :close-on-click-modal="false" :close-on-press-escape="false" @open="$nextTick(()=>$refs['messagebution'].refreshData())" append-to-body>
      <message-bution :display="display" @success="success" @back="dialogMessage=false" @close="emitClose" ref="messagebution"></message-bution>
    </el-dialog>
  </section>
</template>
<script lang="ts">
import Vue from "vue";
import Component from "vue-class-component";

import DepartmentTree from "~/components/system-manage/department-tree.vue";
import { Prop, Emit, Watch } from "vue-property-decorator";
import { Dependencies } from "~/core/decorator";
import { PageService } from "~/utils/page.service";
import { UserService } from "~/services/management-service/user.service";
import { VisitCaseManageService } from "~/services/domain-service/visit-case-manage.service";
import { TelCaseManageService } from "~/services/domain-service/tel-case-manage.service";
import { LegalCaseManageService } from "~/services/domain-service/legal-case-manage.service";
import { CaseAssitVisitStayService } from "~/services/domain-service/case-assist-visit-stay.service";
import { RepairCasesService } from "~/services/domain-service/repair-cases.service";
import { CaseAssistAntiFraudCaseStayService } from '~/services/domain-service/case-assist-anti-fraud-case-stay.service';
import { CaseAssistAntiFraudSurveyCaseService } from "~/services/domain-service/case-assist-anti-fraud-survey-case.service"
import { CaseAssistService } from '~/services/domain-service/case-assist.service';

import Distribution from "~/components/distribution-common/distribution.vue";
import MessageBution from "~/components/distribution-common/message-bution.vue";
import { namespace, Getter } from "vuex-class";
import { CASE_CHANNEL } from "~/config/enum.config";

const AllotModule = namespace("case-allot");

@Component({
  components: {
    DepartmentTree,
    Distribution,
    MessageBution
  }
})
export default class CaseAllot extends Vue {
  @Dependencies(RepairCasesService)
  private repairCasesService: RepairCasesService;
  @Dependencies(PageService) private pageService: PageService;
  @Dependencies(UserService) private userService: UserService;
  @Dependencies(TelCaseManageService)
  private telCaseManageService: TelCaseManageService;
  @Dependencies(VisitCaseManageService)
  private visitCaseManageService: VisitCaseManageService;
  @Dependencies(LegalCaseManageService)
  private legallyCaseManageServiceTestA: LegalCaseManageService;
  @Dependencies(CaseAssitVisitStayService)
  private caseAssitVisitStayService: CaseAssitVisitStayService;
  @Dependencies(CaseAssistAntiFraudCaseStayService)
  private caseAssistAntiFraudCaseStayService: CaseAssistAntiFraudCaseStayService;
  @Dependencies(CaseAssistService)
  private caseAssistService: CaseAssistService;
  @Dependencies(CaseAssistAntiFraudSurveyCaseService)
  private caseAssistAntiFraudSurveyCaseService: CaseAssistAntiFraudSurveyCaseService;
  @Getter private callDepartmentData;
  @Getter private visitDepartmentData;
  @Getter private legalDepartmentData;
  @Getter private creditRepairDepartmentDataNoRoot;
  @Getter private lawDepartmentDataNoRoot;
  @Getter private cheatDepartmentDataNoRoot
  @AllotModule.State private category;
  @AllotModule.Mutation private updateCategory;
  @AllotModule.Mutation private updateDeptIds;
  @AllotModule.Mutation private updateUserIds;
  @AllotModule.Mutation private updateCaseIds;
  @AllotModule.Mutation private updateDebtState;
  @AllotModule.Mutation private updateMode;
  @AllotModule.Getter private distributeModel;
  @AllotModule.Action private resetState: () => void;
  @AllotModule.Mutation private updatePersonalCollectionDays;


  private selectionList: any[] = [];
  private userDataSet: any[] = [];
  private nowNode: any = null;
  private personalCollectionDays: any = null;
  private distributionData: any = {};
  private submitLoading: boolean = false;
  private collectionType = "";
  private dialog = false;
  private dialogMessage = false;

  private DepartmentData = null;
  private currentDept: any = ''
  /**
   * 数据业务来源
   */
  @Prop({ type: String, required: true })
  private fromChannel;

  /**
   * 重新分配
   */
  @Prop({ type: Boolean, default: false })
  private again;

  private get isShow() {
    const arr = [CASE_CHANNEL.assist_tel, CASE_CHANNEL.assist_visit, CASE_CHANNEL.assist_legal]
    return !arr.includes(this.fromChannel) && this.allotType === 'TO_COLLECTOR'
  }

  @Emit("refreshList")
  private emitRefreshList() { }
  @Emit("close")
  private emitClose() {
    this.dialogMessage = false;
    this.dialog = false;
    this.resetState();
    this.currentDept = ''
    this.updateDeptIds()
    this.updateUserIds([])
    this.emitRefreshList()
    this.nowNode = null
    this.DepartmentData = null
    this.personalCollectionDays = null;
    this.allotType = 'TO_COLLECTOR'

  }

  // @Watch("fromChannel", { immediate: true })
  private refreshDept() {
    this.pageService.reset()
    this.userDataSet = [];
    if (!this.fromChannel) return;
    switch (this.fromChannel) {
      case CASE_CHANNEL.tel:
      case CASE_CHANNEL.assist_tel:
        this.DepartmentData = this.callDepartmentData;
        break;
      case CASE_CHANNEL.legal:
      case CASE_CHANNEL.assist_legal:
        this.DepartmentData = this.legalDepartmentData;
        break;
      case CASE_CHANNEL.visit:
      case CASE_CHANNEL.assist_visit:
        this.DepartmentData = this.visitDepartmentData;
        break;
      case CASE_CHANNEL.CREDIT_REPAIR:
        this.DepartmentData = this.creditRepairDepartmentDataNoRoot;
        break;
      case CASE_CHANNEL.law:
        this.DepartmentData = this.lawDepartmentDataNoRoot;
        break;
      case CASE_CHANNEL.fraud:
        this.DepartmentData = this.cheatDepartmentDataNoRoot;
        break
    }
  }

  private get display() {
    return this.allotType === "TO_DEPARTMENT" ? "" : this.selectionList;
  }

  private set display(v: any) {
    this.selectionList = v;
  }

  private get allotType() {
    return this.category;
  }

  private set allotType(val) {
    this.updateCategory(val);
    this.display = [];
  }

  // private get currentDept() {
  //   return this.distributeModel.deptIds[0];
  // }

  // private set currentDept(val) {
  //   this.updateDeptIds(val.id);
  //   this.refreshData(val.deptCode);
  // }

  /**
   * 获取当前树选择项
   */
  private getCheckedNodes(item) {
    if (this.nowNode && item.deptCode === this.nowNode.deptCode) {
      return;
    }
    this.pageService.reset()
    this.currentDept = item;
    this.updateDeptIds(item.id);
    this.refreshData();
  }



  //按机构分配
  private submit() {
    if (!this.currentDept) {
      this.$message.error("请选择部门");
      return false;
    }
    this.updatePersonalCollectionDays('')

    let service: any = null;
    switch (this.fromChannel) {
      case CASE_CHANNEL.tel:
        service = this.telCaseManageService
        break;
      case CASE_CHANNEL.visit:
        service = this.visitCaseManageService
        break;
      case CASE_CHANNEL.legal:
        service = this.legallyCaseManageServiceTestA
        break;
      case CASE_CHANNEL.assist:
      case CASE_CHANNEL.assist_tel:
      case CASE_CHANNEL.assist_visit:
      case CASE_CHANNEL.assist_legal:
        service = this.caseAssistService
        break;
      case CASE_CHANNEL.CREDIT_REPAIR:
        service = this.repairCasesService
        break;
      case CASE_CHANNEL.law:
        service = this.caseAssitVisitStayService
        break;
      case CASE_CHANNEL.fraud:
        service = this.caseAssistAntiFraudCaseStayService
        break;
    }
    if (!service) {
      console.error("分配服务参数配置错误...");
      this.$message.error("案件分配异常");
      return
    }
    this.submitLoading = true
    service.confirmDistributeCase(this.distributeModel).subscribe(data => {
      this.success()
      this.submitLoading = false
    }, () => (this.submitLoading = false));
  }

  private refreshData() {
    const model = {
      deptCode: this.currentDept.deptCode,
      caseSwitch: "ENABLED"
    };
    this.userService
      .getAllUsers(model, this.pageService)
      .subscribe(data => (this.userDataSet = data));
  }

  private next() {
    if (this.isShow) {
      if (!this.personalCollectionDays || this.personalCollectionDays <= 0) {
        return this.$message.error('请输入催收天数！')
      }
      // 更新催收天数
      this.updatePersonalCollectionDays(this.personalCollectionDays)

      // 查询最大催收天数
      this.telCaseManageService
        .getRemainingPartCollectionDays([this.distributeModel.caseIds])
        .subscribe(data => {
          if (data && this.personalCollectionDays > data) {
            return this.$message.error('催收天数不能大于最小部门剩余天数' + data + '天！')
          } else {
            this.updateDebtState(false);
            this.updateMode("BY_INTEGRATE");
            if (this.fromChannel === CASE_CHANNEL.CREDIT_REPAIR) {
              this.dialogMessage = true;
            } else {
              const userIds = this.selectionList.map(v => v.id);
              this.updateUserIds(userIds);
              this.dialog = true;
            }
          }
        });
    } else {
      this.updateDebtState(false);
      this.updateMode("BY_INTEGRATE");
      if (this.fromChannel === CASE_CHANNEL.CREDIT_REPAIR) {
        this.dialogMessage = true;
      } else {
        const userIds = this.selectionList.map(v => v.id);
        this.updateUserIds(userIds);
        this.dialog = true;
      }
    }
  }

  private success() {
    this.$message.success("分配成功");
    this.emitClose();
    this.emitRefreshList();
  }
}
</script>
<style lang="less" scoped>
</style>
